package servlet.admin;

import com.alibaba.fastjson.JSON;
import pojo.Result;
import pojo.User;
import service.UserService;
import service.impl.UserServiceImpl;
import utils.JsonUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.stream.Collectors;

@WebServlet("/admin/editUserServlet")
public class EditUserServlet extends HttpServlet {
    UserService userService = new UserServiceImpl();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String userData = req.getReader().lines().collect(Collectors.joining(System.lineSeparator()));
        User user = JsonUtils.jsonToPojo(userData, User.class);
        Result result = new Result();
        if (user == null) {
            result = Result.error("用户为空");
            // 将 Result 对象转换为 JSON 字符串
            String jsonResponse = JSON.toJSONString(result);
            // 将 JSON 字符串作为响应发送给前端
            resp.getWriter().write(jsonResponse);
        }
        boolean flag = userService.updateUser(user);
        if (flag) {
            result = Result.success();
        } else {
            result = Result.error("修改失败");
        }
        resp.getWriter().write(JSON.toJSONString(result));
    }
}
